package com.yksj.healthtalk.ui.doctorstation;

import java.util.List;

import android.content.BroadcastReceiver;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.TextView;

import com.yksj.healthtalk.comm.BaseFragmentActivity;
import com.yksj.healthtalk.comm.LodingFragmentDialog;
import com.yksj.healthtalk.db.ChatUserHelper;
import com.yksj.healthtalk.entity.MessageEntity;
import com.yksj.healthtalk.net.socket.SmartFoxClient;
import com.yksj.healthtalk.services.MessagePushService;
import com.yksj.healthtalk.ui.R;
import com.yksj.healthtalk.utils.HStringUtil;
import com.yksj.healthtalk.utils.SystemUtils;
import com.yksj.healthtalk.utils.ToastUtil;
/**
 * 医生给患者发通知
 * @author jack_tang
 *
 */
public class DoctorSendMessageToPatients extends BaseFragmentActivity implements OnClickListener {

	private EditText mEditText;
	private final int mCount=1000;
	private TextView textNum;
	private int textNumber = 0;
	final BroadcastReceiver mReceiver = new BroadcastReceiver() {
		public void onReceive(android.content.Context context, Intent intent) {
			if(intent.getAction().equals(MessagePushService.ACTION_REPEAT_STATE)){
				if ("y".equalsIgnoreCase(intent.getStringExtra("FLAG"))) {
					showLodingDialog.dismissAllowingStateLoss();
					ToastUtil.showShort(getApplicationContext(), "发送成功");
					DoctorSendMessageToPatients.this.finish();
//					 好友转发消息需要保存到本地
						Message message = mHandler.obtainMessage();
						message.obj = new MessageEntity[] {(MessageEntity) intent.getSerializableExtra("picture"),
								(MessageEntity) intent.getSerializableExtra("text") };
						message.what = 1;
						mHandler.sendMessage(message);
				} else {
					ToastUtil.showShort(getApplicationContext(), "发送失败");
				}
			}
			
		};
	};
	
	final Handler mHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			// 保存消息到数据库
			if (msg.what == 1) {
				final MessageEntity[] entities = (MessageEntity[]) msg.obj;
				new Thread() {
					public void run() {
						ChatUserHelper helper = ChatUserHelper.getInstance();
						List<String> list =getIntent().getStringArrayListExtra("ids");
						if (entities[0] != null) {
							MessageEntity entity = entities[0];
							for (String id : list) {
								entity.setReceiverId(id);
								helper.insertChatMessage(entity);
							}
						}
						if (entities[1] != null) {
							MessageEntity entity = entities[1];
							for (String id : list) {
								entity.setReceiverId(id);
								helper.insertChatMessage(entity);
							}
						}
					};
				}.start();
			}
		}
	};
	private LodingFragmentDialog showLodingDialog;
	
	@Override
	protected void onCreate(Bundle arg0) {
		super.onCreate(arg0);
		setContentView(R.layout.doctor_send_msg_patients_layout);
		initView();
	}
	@Override
	protected void onStart() {
		super.onStart();
		IntentFilter filter = new IntentFilter(MessagePushService.ACTION_REPEAT_STATE);
		registerReceiver(mReceiver, filter);
	}
	
	@Override
	protected void onStop() {
		super.onStop();
		unregisterReceiver(mReceiver);
	}
	
	private void initView() {
		initTitle();
		findViewById(R.id.send_btn).setOnClickListener(this);
		mEditText = (EditText) findViewById(R.id.setting_feedback_text);
		textNum = (TextView)findViewById(R.id.textcount);
		titleLeftBtn.setOnClickListener(this);
		titleTextV.setText("给患者发通知");
		
		mEditText.addTextChangedListener(new TextWatcher() {
			
			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
				 if((start +count)<=mCount && mEditText.getText().toString().length()<=mCount){
	        		 textNumber = mEditText.getText().toString().length();
	        		 textNum.setText(textNumber+"/"+mCount); 
	        	 }else{
	        		 mEditText.setText(s.subSequence(0, mCount));
	        		 ToastUtil.showShort(DoctorSendMessageToPatients.this, "最多可输入"+mCount+"个字符");
	        	 }
	        }
			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
			}
			@Override
			public void afterTextChanged(Editable s) {
			}
		});
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.title_back:
			onBackPressed();
			break;
		case R.id.send_btn:
			sendMsgFromDoctor();
			break;
		}
	}
	
	private void sendMsgFromDoctor(){
		showLodingDialog = LodingFragmentDialog.showLodingDialog(getSupportFragmentManager(), getResources());
		SystemUtils.hideSoftBord(getApplicationContext(), mEditText);
		if(HStringUtil.isEmpty(mEditText.getText().toString())) return;
		SmartFoxClient.doctorSendMessageToPersons(mEditText.getText().toString(),getIntent().getStringExtra("id"));
	}
}
